﻿/********************************************************************
	created:	2014/01/17
	created:	17:1:2014   14:02
	filename: 	G:\Project\PDAProject\CommonLib\CEUtility.cs
	file path:	G:\Project\PDAProject\CommonLib
	file base:	CEUtility
	file ext:	cs
	author:		Murry
	
	purpose:	WINCE公共库
*********************************************************************/
//#undef WindowsCE
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using NLog;
using System.Data.SqlServerCe;
using System.Data;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.IO;
using System.Globalization;
using System.Xml;
using System.Reflection;

namespace DDASProject.CEUtility
{
    public static class Common
    {
        private static WebService.BarCodeService _svr;
        private static Logger _logger; //日志记录器

        public static WebService.BarCodeService WebSvr
        {
            get { return _svr; }
        }
        public static NLog.Logger Logger
        {
            get { return _logger; }
        }
        static Common()
        {
            _svr = new WebService.BarCodeService();
            _svr.Url = GetGlobalSetting("DefaultUrl");
            _logger = LogManager.GetLogger("Logger");
        }

#if     WindowsCE
        [DllImport("coredll.dll", EntryPoint = "CreateMutex", SetLastError = true)]
        public static extern IntPtr CreateMutex(
        IntPtr lpMutexAttributes,
        bool InitialOwner,
        string MutexName);

        [DllImport("coredll.dll", EntryPoint = "ReleaseMutex", SetLastError = true)]
        public static extern bool ReleaseMutex(IntPtr hMutex);

        [DllImport("coredll.dll", SetLastError = true)]
        private static extern bool PlaySound(string pszSound, IntPtr hmod, uint fdwSound);  //播放声音

        [DllImport("coredll.dll")]
        private static extern int FindWindow(string lpClassName, string lpWindowName);//状态栏操作
        [DllImport("coredll.dll")]
        internal extern static int EnableWindow(int hwnd, int fEnable);
        [DllImport("coredll.dll")]
        public static extern int ShowWindow(int hwnd, int nCmdShow);


        public enum PlaySoundFlags : uint
        {
            SND_ASYNC = 1,
            SND_FILENAME = 0x20000,
            SND_LOOP = 8,
            SND_MEMORY = 4,
            SND_NODEFAULT = 2,
            SND_NOSTOP = 0x10,
            SND_NOWAIT = 0x2000,
            SND_RESOURCE = 0x40004,
            SND_SYNC = 0
        }


        private const int ERROR_ALREADY_EXISTS = 0183;

        /// <summary>  
        /// 判断程序是否已经运行  
        /// </summary>  
        /// <returns>  
        /// true: 程序已运行，则什么都不做  
        /// false: 程序未运行，则启动程序  
        /// </returns>  
        public static bool IsExist()
        {
            IntPtr hMutex = CreateMutex(IntPtr.Zero, true, "gzeliteDDAS");
            if (hMutex == IntPtr.Zero)
                throw new ApplicationException("Failure creating mutex: "
                + Marshal.GetLastWin32Error().ToString("X"));

            if (Marshal.GetLastWin32Error() == ERROR_ALREADY_EXISTS)
            {
                ReleaseMutex(hMutex);
                return true;
            }
            return false;

        }
        //铃声
        public static void PlayAlarm()
        {
            uint fdwSound = Convert.ToUInt32(PlaySoundFlags.SND_ASYNC | PlaySoundFlags.SND_FILENAME);
            PlaySound("voicbeep.wav", IntPtr.Zero, fdwSound);
        }
        //错误声音
        public static void PlayWarning()
        {
            uint fdwSound = Convert.ToUInt32(PlaySoundFlags.SND_FILENAME);
            PlaySound("error.wav", IntPtr.Zero, fdwSound);
        }

        private static int hTaskBarWnd = 0;

        /// <summary>
        /// 调整任务栏
        /// </summary>
        /// <param name="form">窗口对象</param>
        /// <param name="isHide">true:隐藏任务栏,false:显示状态栏</param>
        public static void HideTaskBar(System.Windows.Forms.Form form, bool isHide)
        {
            //   this.TopMost = true;
            form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            hTaskBarWnd = FindWindow("HHTaskBar", null);
            if (isHide)
            {
                ShowWindow(hTaskBarWnd, 0);//隐藏状态栏
            }
            else
            {
                ShowWindow(hTaskBarWnd, 1);//显示状态栏
            }

        }
        /// <summary>
        /// 自动调整窗口布局
        /// </summary>
        /// <param name="form"></param>
        public static void Adapt(System.Windows.Forms.Form form)//自适应
        {
            form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            double dFinalWidth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;//屏幕宽
            double dFinalHeigth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;//屏幕高

            double dXZoom = dFinalWidth / form.Width;//放大系数
            double dYZoom = dFinalHeigth / form.Height;

            form.Width = (int)dFinalWidth;//全屏显示
            form.Height = (int)dFinalHeigth;

            setControls(form.Controls, dXZoom, dYZoom, dFinalHeigth);
            // this.TopMost = true;
        }

        private static void setControls(System.Windows.Forms.Control.ControlCollection controls, double dXZoom, double dYZoom, double dFinalHeigth)
        {

            foreach (System.Windows.Forms.Control c in controls)//遍历所有控件
            {
                //  Debuge("分辨率x:" + dFinalWidth + "\ny:" + dFinalHeigth + "\n");

                c.Location = new System.Drawing.Point((int)((double)c.Left * dXZoom), (int)((double)c.Top * dYZoom));

                c.Width = (int)((double)c.Width * dXZoom);
                c.Height = (int)((double)c.Height * dYZoom);

                //         Single currentSize = (float)(c.Font.Size * dYZoom);

                //3.5寸屏字体
                if (dFinalHeigth < 260)
                {
                    try
                    {
                        c.Font = new Font(c.Font.Name, 8, c.Font.Style);
                    }
                    catch (Exception)
                    {

                    }
                }

                //4.3寸屏字体
                if (260 <= dFinalHeigth && dFinalHeigth <= 300)
                {
                    try
                    {
                        c.Font = new Font(c.Font.Name, 11, c.Font.Style);
                    }
                    catch (Exception)
                    {

                    }
                }
                //4.3寸屏以上字体
                if (dFinalHeigth > 300)
                {
                    try
                    {
                        c.Font = new Font(c.Font.Name, 13, c.Font.Style);
                    }
                    catch (Exception)
                    {

                    }
                }

            }

        }
#endif



        /// <summary>
        /// 获取程序集版本号
        /// </summary>
        /// <param name="assembly"></param>
        /// <returns></returns>
        public static Version GetModuleVersion(Assembly assembly)
        {

            return assembly.GetName().Version;
        }
        /// <summary>
        /// 解密函数
        /// </summary>
        /// <param name="pToDecrypt">内容</param>
        /// <param name="sKey">密钥</param>
        /// <returns></returns>
        public static string Decrypt(string pToDecrypt, string sKey)
        {
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            byte[] buffer = new byte[pToDecrypt.Length / 2];
            for (int i = 0; i < (pToDecrypt.Length / 2); i++)
            {
                int num2 = Convert.ToInt32(pToDecrypt.Substring(i * 2, 2), 0x10);
                buffer[i] = (byte)num2;
            }
            provider.Key = Encoding.ASCII.GetBytes(sKey);
            provider.IV = Encoding.ASCII.GetBytes(sKey);
            MemoryStream stream = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
            stream2.Write(buffer, 0, buffer.Length);
            stream2.FlushFinalBlock();
            StringBuilder builder = new StringBuilder();
            byte[] bytes = stream.ToArray();
            return Encoding.Default.GetString(bytes, 0, bytes.Length);
        }

        /// <summary>
        /// 加密函数
        /// </summary>
        /// <param name="pToEncrypt">内容</param>
        /// <param name="sKey">密钥</param>
        /// <returns></returns>
        public static string Encrypt(string pToEncrypt, string sKey)
        {
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            byte[] bytes = Encoding.Default.GetBytes(pToEncrypt);
            provider.Key = Encoding.ASCII.GetBytes(sKey);
            provider.IV = Encoding.ASCII.GetBytes(sKey);
            MemoryStream stream = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
            stream2.Write(bytes, 0, bytes.Length);
            stream2.FlushFinalBlock();
            StringBuilder builder = new StringBuilder();
            CultureInfo currentCulture = CultureInfo.CurrentCulture;
            foreach (byte num in stream.ToArray())
            {
                builder.AppendFormat(currentCulture, "{0:X2}", new object[] { num });
            }
            builder.ToString();
            return builder.ToString();
        }




        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="folderName"></param>
        public static string CreateFolder(string folderName)
        {
            string fullPath = "";
            try
            {
                fullPath = Path.Combine(Common.ApplicationPath, folderName);

                if (!Directory.Exists(fullPath))
                {
                    Directory.CreateDirectory(fullPath);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return fullPath;
        }

        /// <summary>
        /// 通过程序ID获取程序名
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetAppNameByID(AppID id)
        {
            String name = "";
            switch (id)
            {
                case AppID.CaigouShouhuo:
                    name = "采购收货";
                    break;
                case AppID.CaiqieWeihu:
                    name = "裁切维护";
                    break;
                case AppID.CangkuTuiliao:
                    name = "仓库退料";
                    break;
                case AppID.ChaiheBiaoqian:
                    name = "拆合标签";
                    break;
                case AppID.ChengpinChuhuo:
                    name = "成品出货";
                    break;
                case AppID.DiaoboZuoye:
                    name = "调拨作业";
                    break;
                case AppID.ElectrolyticPaper:
                    name = "电解纸发料";
                    break;
                case AppID.GongdanFaliao:
                    name = "工单发料";
                    break;
                case AppID.HeXiang:
                    name = "核箱";
                    break;
                case AppID.Pandian:
                    name = "盘点";
                    break;
                case AppID.StockTaking:
                    name = "标签补打";
                    break;
                case AppID.XiaotuiZuoye:
                    name = "销退作业";
                    break;
                case AppID.ZashouZafa:
                    name = "杂收杂发";
                    break;
                case AppID.CEUtility:
                    name = "PDA公共单元库";
                    break;
                case AppID.Update:
                    name = "自动更新程序";
                    break;
                case AppID.MaterialAllot:
                    name = "材料调拨";
                    break;
                default:
                    break;
            }
            return name;
        }

        /// <summary>
        /// 检测程序是否有更新
        /// </summary>
        /// <param name="assembly">输入程序assembly对象</param>
        /// <param name="appID">输入程序ID</param>
        /// <param name="downloadUrl">输出下载地址</param>
        /// <returns>-1:错误,0没有更新,1:有更新,2:系统强制更新</returns>
        public static int CheckUpdata(Assembly assembly, AppID appID, out string downloadInfo)
        {
            int ret = -1;
            downloadInfo = "";
            try
            {
                Version curVer = Common.GetModuleVersion(assembly); //获取当前程序版本            
                if (null == _svr)
                {
                    _svr = new WebService.BarCodeService();
                    _svr.Url = GetGlobalSetting("DefaultUrl");
                }
                string info = _svr.GetAppInfomation((int)appID);
                downloadInfo = info;
                if (!string.IsNullOrEmpty(info))
                {
                    string[] infoArr = info.Split(';');
                    if (null != infoArr && infoArr.Length > 4)
                    {
                        //string appName = infoArr[0]; //文件名
                        string version = infoArr[1]; //版本号
                        string bForce = infoArr[2]; //是否强制更新
                        //downloadUrl = infoArr[3]; //下载地址
                        //string description = infoArr[4]; //更新内容                
                        Version newVer = new Version(version);
                        if (curVer < newVer && bForce == "1") //有新版本发布,强制更新
                        {
                            ret = 2;                        
                        }                       
                        else if (curVer < newVer) //有新版本发布,非强制更新
                        {
                            ret = 1;                            
                        }
                        else //没有更新
                        {
                            ret = 0;
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                _logger.Error(ex);
            }

            return ret;
        }

        private static string _applicationPath; //程序运行平台
        private static string Platform
        {
            get
            {
                return Environment.OSVersion.Platform.ToString();
            }
        }

        public static bool IsWinCEPlatform
        {
            get { return Platform == "WinCE" ? true : false; }
        }
        /// <summary>
        /// 获取当前系统程序的运行目录
        /// </summary>
        public static string ApplicationPath
        {
            get
            {
                if (Platform.Equals("WinCE"))
                {
                    _applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
                }
                else if (Platform.Equals("Win32NT"))
                {
                    _applicationPath = System.IO.Directory.GetCurrentDirectory();
                }
                return _applicationPath;
            }
        }

        /// <summary>
        /// 获取配置程序路径
        /// </summary>
        public static string AppSettingPath
        {
            get
            {
                return Path.Combine(ApplicationPath, "AppSettings.exm");
            }
        }

        /// <summary>
        /// 获取对应程序配置属性
        /// </summary>
        /// <param name="appName">程序名</param>
        /// <param name="keyName">属性名</param>
        /// <returns></returns>
        public static string GetAppSetting(string appName, string keyName)
        {
            string strRet = string.Empty;
            try
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(AppSettingPath);
                var root = xmlDoc.SelectSingleNode("ConfigDoc");
                var nodeList = root.SelectNodes("Section");
                string name = string.Empty;

                if (null != nodeList)
                {
                    foreach (XmlNode node in nodeList)
                    {
                        if (node.Attributes["name"].Value == "LocalSettings" && node.HasChildNodes)
                        {
                            var nodeList2 = node.ChildNodes;
                            foreach (XmlNode node2 in nodeList2)
                            {
                                if (node2.Attributes["name"].Value == appName && node2.HasChildNodes)
                                {
                                    foreach (XmlNode node3 in node2)
                                    {
                                        if (node3.Attributes["name"].Value.ToLower() == keyName.ToLower())
                                        {
                                            strRet = node3.InnerText;
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                        
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw ex;

            }
            return strRet;
        }

        /// <summary>
        /// 获取全局配置
        /// </summary>
        /// <param name="keyName">属性名</param>
        /// <returns></returns>
        public static string GetGlobalSetting(string keyName)
        {
            string strRet = string.Empty;
            try
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(AppSettingPath);
                var root = xmlDoc.SelectSingleNode("ConfigDoc");
                var nodeList = root.SelectNodes("Section");
                string name = string.Empty;

                if (null != nodeList)
                {
                    foreach (XmlNode node in nodeList)
                    {
                        if (node.Attributes["name"].Value == "GlobalSettings" &&　node.HasChildNodes)
                        {
                            var nodeList2 = node.ChildNodes;
                            foreach (XmlNode node2 in nodeList2)  //key
                            {
                                if (node2.Attributes["name"].Value.ToLower() == keyName.ToLower())
                                {
                                    strRet = node2.InnerText;
                                    break;
                                }
                                
                            }
                            break;
                        }                        
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw ex;

            }
            return strRet;
        }

        /// <summary>
        /// 设置全局配置区
        /// </summary>
        /// <param name="keyName">属性名</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        public static bool SetGlobalSetting(string keyName, string keyValue)
        {
            bool bRet = false;
            try
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(AppSettingPath);
                var root = xmlDoc.SelectSingleNode("ConfigDoc");
                var nodeList = root.SelectNodes("Section");
                string name = string.Empty;

                if (null != nodeList)
                {
                    foreach (XmlNode node in nodeList)
                    {
                        if (node.Attributes["name"].Value == "GlobalSettings"  && node.HasChildNodes)
                        {
                            var nodeList2 = node.ChildNodes;
                            foreach (XmlNode node2 in nodeList2)  //key
                            {
                                if (node2.Attributes["name"].Value == keyName)
                                {
                                    node2.InnerText = keyValue;
                                    break;
                                }                                
                            }
                            break;
                        }
                        
                    }
                }
                xmlDoc.Save(AppSettingPath);
            }
            catch (System.Exception ex)
            {
                throw ex;

            }
            return bRet;
        }


        /// <summary>
        /// 设置应用程序区段
        /// 只能改变值,无法增加设置区段
        /// </summary>
        /// <param name="appName">程序名</param>
        /// <param name="keyName">属性</param>
        /// <param name="keyValue">值</param>
        /// <returns></returns>
        public static bool SetAppSetting(string appName, string keyName, string keyValue)
        {
            bool bRet = false;
            try
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(AppSettingPath);
                var root = xmlDoc.SelectSingleNode("ConfigDoc");
                var nodeList = root.SelectNodes("Section");
                string name = string.Empty;

                if (null != nodeList)
                {
                    foreach (XmlNode node in nodeList)
                    {
                        if (node.Attributes["name"].Value == "LocalSettings" && node.HasChildNodes)
                        {
                            var nodeList2 = node.ChildNodes;
                            foreach (XmlNode node2 in nodeList2)
                            {
                                if (node2.Attributes["name"].Value != appName || !node2.HasChildNodes)
                                {
                                    continue;
                                }

                                foreach (XmlNode node3 in node2)
                                {
                                    if (node3.Attributes["name"].Value == keyName)
                                    {
                                        node3.InnerText = keyValue;
                                    }
                                    break;
                                }
                            }
                            break;
                        }
                        
                    }
                }
                xmlDoc.Save(AppSettingPath);
            }
            catch (System.Exception ex)
            {
                throw ex;

            }
            return bRet;
        }

        /// <summary>
        /// 添加节点
        /// </summary>
        /// <param name="appName">程序名</param>
        /// <param name="keyName">属性名</param>
        /// <param name="keyValue">值</param>
        /// <param name="description">描述</param>
        /// <returns></returns>
        public static bool AddAppSetting(string appName, string keyName, string keyValue, string description)
        {
            bool bRet = false;
            try
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(AppSettingPath);
                var root = xmlDoc.SelectSingleNode("ConfigDoc");
                var nodeList = root.SelectNodes("Section");
                string name = string.Empty;

                if (null != nodeList)
                {
                    foreach (XmlNode node in nodeList)
                    {
                        if (node.Attributes["name"].Value == "LocalSettings" && node.HasChildNodes)
                        {
                            var nodeList2 = node.ChildNodes;
                            foreach (XmlNode node2 in nodeList2) //查找对应程序区段
                            {
                                if (node2.Attributes["name"].Value == appName)
                                {
                                    bool isExistKey = false;
                                    foreach (XmlNode node3 in node2) //查找是已否存在此配置属性
                                    {
                                        if (node3.Attributes["name"].Value == keyName) //找到就直接赋值
                                        {
                                            node3.InnerText = keyValue;
                                            isExistKey = true;
                                        }
                                    }
                                    if (!isExistKey) //没找到就增加对应区段
                                    {
                                        XmlElement newNode = xmlDoc.CreateElement("Key");
                                        newNode.SetAttribute("falgs", "16");
                                        newNode.SetAttribute("name", keyName);
                                        newNode.SetAttribute("desc", description);
                                        newNode.InnerText = keyValue;
                                        node2.AppendChild(newNode);
                                    }
                                    break;
                                }

                            }
                            break;
                        }
                       
                    }
                }
                xmlDoc.Save(AppSettingPath);
            }
            catch (System.Exception ex)
            {
                throw ex;

            }
            return bRet;
        }
    }



    #region SQLCE辅助类


    public static class SqlCeHelper
    {
        public static object ExecuteScalar(SqlCeConnection conn, string cmdText, params SqlCeParameter[] parameters)
        {
            if (null == conn || string.IsNullOrEmpty(cmdText))
            {
                throw new ArgumentNullException("conn或cmdText不能为空");
            }
            object objRet = null;
            try
            {
                if (conn.State != System.Data.ConnectionState.Open)
                {
                    conn.Open();
                }
                using (SqlCeCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = cmdText;
                    if (null != parameters)
                    {
                        foreach (SqlCeParameter p in parameters)
                        {
                            cmd.Parameters.Add(p);
                        }
                    }
                    objRet = cmd.ExecuteScalar();
                    if (DBNull.Value.Equals(objRet))
                        objRet = null;
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
            return objRet;
        }
        public static object ExecuteScalar(SqlCeConnection conn, string cmdText)
        {
            return ExecuteScalar(conn, cmdText, null);
        }
        public static int ExecuteNonQuery(SqlCeConnection conn, string cmdText, params SqlCeParameter[] parameters)
        {
            if (null == conn || string.IsNullOrEmpty(cmdText))
            {
                throw new ArgumentNullException("conn或cmdText不能为空");
            }
            int nRet = 0;
            try
            {
                if (conn.State != System.Data.ConnectionState.Open)
                {
                    conn.Open();
                }
                using (SqlCeCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = cmdText;
                    if (null != parameters)
                    {
                        foreach (SqlCeParameter p in parameters)
                        {
                            cmd.Parameters.Add(p);
                        }
                    }
                    nRet = cmd.ExecuteNonQuery();
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
            return nRet;
        }

        public static int ExecuteNonQuery(SqlCeConnection conn, string cmdText)
        {
            return ExecuteNonQuery(conn, cmdText, null);
        }

        public static SqlCeDataReader ExecuteReader(SqlCeConnection conn, string cmdText, params SqlCeParameter[] parameters)
        {
            if (null == conn || string.IsNullOrEmpty(cmdText))
            {
                throw new ArgumentNullException("conn或cmdText不能为空");
            }
            SqlCeDataReader readRet = null;
            try
            {
                if (conn.State != System.Data.ConnectionState.Open)
                {
                    conn.Open();
                }
                using (SqlCeCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = cmdText;
                    if (null != parameters)
                    {
                        foreach (SqlCeParameter p in parameters)
                        {
                            cmd.Parameters.Add(p);
                        }
                    }
                    readRet = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }

            return readRet;
        }

        public static SqlCeDataReader ExecuteReader(SqlCeConnection conn, string cmdText)
        {
            return ExecuteReader(conn, cmdText, null);
        }

        public static SqlCeResultSet ExecuteResultSet(SqlCeConnection conn, string cmdText, params SqlCeParameter[] parameters)
        {
            if (null == conn || string.IsNullOrEmpty(cmdText))
            {
                throw new ArgumentNullException("conn或cmdText不能为空");
            }
            SqlCeResultSet rstRet = null;
            try
            {
                if (conn.State != System.Data.ConnectionState.Open)
                {
                    conn.Open();
                }
                using (SqlCeCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = cmdText;
                    if (null != parameters)
                    {
                        foreach (SqlCeParameter p in parameters)
                        {
                            cmd.Parameters.Add(p);
                        }
                    }
                    ResultSetOptions options = ResultSetOptions.Scrollable | ResultSetOptions.Updatable | ResultSetOptions.Sensitive;
                    rstRet = cmd.ExecuteResultSet(options);
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }

            return rstRet;
        }

        public static SqlCeResultSet ExecuteResultSet(SqlCeConnection conn, string cmdText)
        {
            return ExecuteResultSet(conn, cmdText, null);
        }

        public static DataSet ExecuteDataSet(SqlCeConnection conn, string cmdText, params SqlCeParameter[] parameters)
        {
            if (null == conn || string.IsNullOrEmpty(cmdText))
            {
                throw new ArgumentNullException("conn或cmdText不能为空");
            }
            DataSet dsRet = null;
            try
            {
                if (conn.State != System.Data.ConnectionState.Open)
                {
                    conn.Open();
                }
                using (SqlCeCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = cmdText;
                    if (null != parameters)
                    {
                        foreach (SqlCeParameter p in parameters)
                        {
                            cmd.Parameters.Add(p);
                        }
                    }
                    using (SqlCeDataAdapter ceda = new SqlCeDataAdapter(cmd))
                    {
                        dsRet = new DataSet("myDataSet");
                        ceda.Fill(dsRet);
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }

            return dsRet;
        }

        public static DataSet ExecuteDataSet(SqlCeConnection conn, string cmdText)
        {
            return ExecuteDataSet(conn, cmdText, null);
        }

        public static DataTable ExecuteDataTabe(SqlCeConnection conn, string cmdText, params SqlCeParameter[] parameters)
        {
            DataTable dt = null;
            DataSet ds = ExecuteDataSet(conn, cmdText, parameters);
            if (null != ds && null != ds.Tables && ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }
            return dt;
        }

        public static DataTable ExecuteDataTabe(SqlCeConnection conn, string cmdText)
        {
            return ExecuteDataTabe(conn, cmdText, null);
        }
    }

   
    #endregion

    public class WaitCursor : IDisposable
    {
        private static int _refCount;

        static WaitCursor()
        {
        }

        public WaitCursor()
        {
            if (WaitCursor._refCount == 0)
            {
                System.Windows.Forms.Cursor.Current =   System.Windows.Forms.Cursors.WaitCursor;
                System.Windows.Forms.Cursor.Show();
            }
            WaitCursor._refCount = WaitCursor._refCount + 1;
        }

        public void Dispose()
        {
            WaitCursor._refCount = WaitCursor._refCount - 1;
            if (WaitCursor._refCount < 0)
            {
                WaitCursor._refCount = 0;
            }
            if (WaitCursor._refCount == 0)
            {
                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
                System.Windows.Forms.Cursor.Hide();
            }
        }
    }
}
